<template>
  <tl-sub-page :append-to-body="true" :render="render" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog taskab" width="1000px" @open="open" @close="close">
    <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="170px" :disabled="disableEditSubmit">
      <el-row>
        <el-col :span="24">
          <el-form-item label="所属里程碑及任务" prop="milepostname" :rules="rules.validateRequire">
            <el-input v-model="model.milepostname" disabled class="tl-ref-selector">
              <el-button slot="append" type="primary" icon="el-icon-search" @click="openMpmProjectMilepostDialog" v-if="!disableBytaskstate"></el-button>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="任务类型" prop="tasktype" :rules="rules.validateRequire">
            <el-select v-model="model.tasktype" filterable clearable>
              <el-option v-for="item in codeModel.tasktypeList" :key="item.code" :label="item.name"
                :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="优先级" prop="taskpriority" :rules="rules.validateRequire">
            <el-select v-model="model.taskpriority" filterable clearable>
              <el-option v-for="item in codeModel.taskpriorityList" :key="item.code" :label="item.name"
                :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-row>
        <el-col :span="12">
          <el-row :gutter="8">
            <el-col :span="22">
              <el-form-item label="任务名称" prop="taskname" :rules="rules.validateRequire">
                <el-input v-model.trim="model.taskname" :disabled="disableBytaskstate || model.istemplate === '1' || model.wbstemplateflag === 1"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2" v-show="model.taskexplain">
              <el-tooltip :content="model.taskexplain" placement="top" style="font-size:20px; margin-top:4px">
                <i class="el-icon-info" style="color: #909399"/>
              </el-tooltip>
            </el-col>
          </el-row>
        </el-col>

      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="任务内容" prop="taskdetail" :rules="rules.validateRequire">
            <el-input v-model="model.taskdetail" type="textarea" maxlength="1000" show-word-limit :autosize="{ minRows:1, maxRows:3 }" :disabled="disableBytaskstate"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="责任人" prop="responsible" :rules="rules.validateRequire">
            <tl-ref-stakeholder v-model="model.responsible" :initDisplayData.sync="model.responsible" fieldKey="usercode" @confirm="getmpmProjectStakeData" :externalSelectedRowKeys="model.responsiblecode" title="选择任务责任人" :externalQueryParam="externalQueryParamForStakeholder" :isSingleSelect="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="责任人工号" prop="responsiblecode" :rules="rules.validateRequire">
            <el-input v-model="model.responsiblecode" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划开始日期" prop="planstartdate" :rules="rules.validateRequire">
            <el-date-picker v-model="model.planstartdate" type="date" :disabled="disableBytaskstate" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" @change="changeTaskPlanStartDate">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划完成日期" prop="planenddate" :rules="rules.validateRequire">
            <el-date-picker v-model="model.planenddate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd " @change="changeTaskPlanEndDate">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="tl-form-line-title" v-if="customerTaskFlag">
        客户决策分析
      </div>
      <el-row v-if="customerTaskFlag">
        <el-col :span="12">
          <el-row :gutter="8">
            <el-col :span="22">
              <el-form-item label="关键决策客户部门职务" prop="post">
                <el-input v-model="model.post" :disabled="disableEditSubmit"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-tooltip content="识别本任务决策链的决策客户，填写单位、部门和职务，例：省营销部计量处 处长、xx市营销部 副主任。" placement="top" style="font-size:20px; margin-top:4px">
                <i class="el-icon-info" style="color: #909399"/>
              </el-tooltip>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="12">
          <el-row :gutter="8">
            <el-col :span="22">
              <el-form-item label="任务支持程度" prop="customerapproval">
                <el-select v-model="model.customerapproval" filterable clearable :disabled="disableEditSubmit">
                  <el-option v-for="item in codeModel.customerapprovalList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-tooltip content="抛开日常客户关系，针对本任务客户从业务需求层面的真实支持情况。" placement="top" style="font-size:20px; margin-top:4px">
                <i class="el-icon-info" style="color: #909399"/>
              </el-tooltip>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row v-if="customerTaskFlag" :gutter="8">
        <el-col :span="23">
          <el-form-item label="客户接触现状" prop="customerattach">
            <el-input v-model="model.customerattach" type="textarea" maxlength="1000" show-word-limit :autosize="{ minRows:1, maxRows:3 }" :disabled="disableEditSubmit"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-tooltip content="针对本任务清晰表述客户接触现状和达成任务的差距（根因）。例：前期客户接触，对我司专业度认识不够，与客户交流X批次x产品招标技术规范更新，客户未认可我方提出的xx技术参数，认为不可实现，目前未同意。" placement="top" style="font-size:20px; margin-top:4px">
            <i class="el-icon-info" style="color: #909399"/>
          </el-tooltip>
        </el-col>
      </el-row>
      <el-row v-if="customerTaskFlag">
        <el-col :span="12">
          <el-form-item label="是否需要系统部支持" prop="needsupport">
            <el-select v-model="model.needsupport" filterable clearable :disabled="disableEditSubmit">
              <el-option v-for="item in codeModel.needsupportList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="customerTaskFlag" :gutter="8">
        <el-col :span="23">
          <el-form-item label="客户关系改善计划" prop="improveplan">
            <el-input v-model="model.improveplan" type="textarea" maxlength="1000" show-word-limit :autosize="{ minRows:1, maxRows:3 }" :disabled="disableEditSubmit"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-tooltip content="针对本任务清晰表述如何弥补差距，明确时间、形式、内容和目标。例：2022年4月10日前，计划安排公司产品线和质量部拜访交流，针对xx技术指标的必要性进行技术交流和论证，使客户认可该项技术指标的必要性和可实现性，从而支持修改招标技术规范。" placement="top" style="font-size:20px; margin-top:4px" v-if="!isdirector">
            <i class="el-icon-info" style="color: #909399"/>
          </el-tooltip>
          <el-tooltip content="接触项目省级业务部门主任（营销部、设备部、建设部等），明确项目运作过程中业务部门主任接触沟通计划。例：2022年4月10日前，项目培育阶段，向营销部主任，表达参与意愿；2022年6月10日前，项目招标挂网，向营销部主任，汇报我方参与情况；2022年7月10日，项目结果公示，向营销部主任，表达支持感谢。" placement="top" style="font-size:20px; margin-top:4px" v-if="isdirector">
            <i class="el-icon-info" style="color: #909399"/>
          </el-tooltip>
        </el-col>
      </el-row>
      <tl-feedback-line ref="feedbackRef" style="margin-top: 20px" :fromGantt="fromGantt"></tl-feedback-line>
    </el-form>
  </tl-sub-page>
</template>

<script>
  /** mixins */
  import { mixin_edit } from '@tapui/mixins/mixin_edit'
  /** 子组件 */
  import tlmpmProjectMilepostRef from '@/views/mpm/mpmProjectMilepost/refList'
  import tlRefStakeholder from "../mpmProjectStakeholder/refList"
  import tlFeedbackLine from '../mpmProjectTaskFeedback/feedbackLine'

  /** 工具类 */
  import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
  import { MPM_TASK_STATE, MPM_TASK_TEMPLATE_TYPE } from '@/const/const'
  import { validateNull } from '@tapui/utils/validate'
  import { formatDate } from '@tapui/utils/date'
  /** VUE配置 */
  export default {
    mixins: [mixin_edit],
    components: { tlmpmProjectMilepostRef, tlRefStakeholder, tlFeedbackLine, MPM_TASK_STATE },
    data() {
      return {
        moduleTitle: '项目任务',
        urlPrefix: '/mpm/projectTask/',
        url: {
          // 额外的url
          updateResponsible: 'mpm/projectTask/updateResponsible',
          checkProjectALevel: '/mpm/projectPlan/checkProjectALevel',
          distributeTask: '/mpm/projectTask/distributeTask',
          milepostlist: '/mpm/projectMilepost/list',
          updateAbnormalState: '/mpm/project/updateAbnormalState',
          updateGap: '/mpm/projectTaskFeedback/updateGap'
        },
        externalQueryParamForPool: {},
        // 人员组件查询参数
        externalQueryParamForStakeholder: {
          qry_projectcode: '' // 项目编号
        },
        projectALevelFlag: false,
        oldresponsiblecode: '',
        milepostPlanFinishTime: '',
        oldplanenddate: 0,
        submitLoading: false,
        projectcode: ''
      }
    },
    props: {
      projectinfo: {
        type: Object,
        default() {
          return {}
        }
      },
      render: {
        default: 'el-dialog',
        type: String
      },
      fromGantt: {
        default: false,
        type: Boolean
      }
    },
    computed: {
      // 表单组件禁用
      disableBytaskstate() {
        if (this.model.taskstate === MPM_TASK_STATE.notStart) {
          return false
        }
        return true
      },
      customerTaskFlag() {
        return this.projectALevelFlag
      },
      // 下发按钮的显示/隐藏
      showDistrbuteButton() {
        // 下发前编辑状态时显示
        return !this.isAdd && !this.disableEditSubmit && this.model.state === 0
      },
      isdirector() {
        return this.codeModel.mpmsystemtasknameList && this.codeModel.mpmsystemtasknameList.length > 7 ? this.codeModel.mpmsystemtasknameList[7].name === this.model.taskname : false
      }
    },
    methods: {
      // 实时更新项目状态
      updateAbnormalState() {
        putAction(this.url.updateAbnormalState, { projectcode: this.model.projectcode })
          .then((res) => {
            if (res.success) {
              // 若更新了项目状态则提示
              if (res.result.changeState) {
                // 套娃回调更新项目状态
                this.$emit('refresh', true)
              }
            } else {
              this.$tap.alert(res.message, 'warning')
            }
          })
          .catch((err) => {
            this.$tap.alert(err.message, 'warning')
          })
      },
      /** 提交后执行 */
      afterSubmit() {
        let newplanenddate = new Date(this.model.planenddate).getTime()
        let currentdate = new Date()
        currentdate.setHours(0, 0, 0, 0)
        currentdate = currentdate.getTime()
        // 若修改了计划完成日期，旧计划完成日期小于当前日期，且新计划完成日期大于当前日期则执行实时更新项目状态方法
        if (this.oldplanenddate !== newplanenddate && this.oldplanenddate < currentdate && newplanenddate > currentdate) {
          this.updateAbnormalState()
          this.oldplanenddate = new Date(this.model.planenddate).getTime()
        }
      },
      // 查询里程碑及任务信息
      queryMilepost(milepostcode) {
        let param = {
          qry_operatecode: milepostcode
        }
        getAction(this.url.milepostlist, param).then((res) => {
          if (res.success) {
            // 如果有多个里程碑及任务,选择enabled = 1的里程碑及任务，如果只有一个里程碑及任务（首次策划），选择此里程碑及任务
            if (res.result.dataList.length === 1) {
              this.milepostPlanFinishTime = res.result.dataList[0].planfinishtime
            } else {
              let resultList = res.result.dataList.filter(item => item.enabled === 1)
              this.milepostPlanFinishTime = resultList[0]
            }
          } else {
            this.$tap.alert(res.message, 'warning')
          }
        })
      },
      // 计划完成日期监听
      changeTaskPlanEndDate() {
        if (this.model.planenddate === null) {
          return
        }
        // 没选里程碑及任务就没有里程碑及任务达成日期，无法校验
        if (!this.milepostPlanFinishTime) {
          this.$tap.alert('请先选择任务所属里程碑及任务！', 'warning')
          this.$set(this.model, 'planenddate', null)
          return
        }
        if (!this.model.planstartdate) {
          this.$tap.alert('请先填写任务的计划开始日期！', 'warning')
          this.$set(this.model, 'planenddate', null)
          return
        }
        // 若计划开始日期大于计划完成日期则提示
        if (this.formatDateToMicro(this.model.planenddate) < this.formatDateToMicro(this.model.planstartdate)) {
          this.$tap.alert('任务的计划开始日期不能大于计划完成日期！', 'warning')
          this.$set(this.model, 'planenddate', null)
          return
        }
        // 若任务计划完成日期大于里程碑及任务日期则提示
        if (this.formatDateToMicro(this.model.planenddate) > this.formatDateToMicro(this.milepostPlanFinishTime)) {
          this.$tap.alert('任务的计划完成日期不能大于所属里程碑及任务的计划达成日期！', 'warning')
          this.$set(this.model, 'planenddate', null)
          return
        }
      },
      // 计划开始日期监听
      changeTaskPlanStartDate() {
        if (this.model.planstartdate === null) {
          return
        }
        // 没选里程碑及任务就没有里程碑及任务达成日期，无法校验
        if (!this.milepostPlanFinishTime) {
          this.$tap.alert('请先选择任务所属里程碑及任务！', 'warning')
          this.$set(this.model, 'planstartdate', null)
          return
        }
        if (this.model.planenddate && this.formatDateToMicro(this.model.planstartdate) > this.formatDateToMicro(this.model.planenddate)) {
          this.$tap.alert('任务计划开始日期不能晚于任务计划完成时间！')
          this.$set(this.model, 'planstartdate', null)
          return
        }
        // 若任务计划开始日期大于里程碑及任务日期则提示
        if (this.formatDateToMicro(this.model.planstartdate) > this.formatDateToMicro(this.milepostPlanFinishTime)) {
          this.$tap.alert('任务的计划开始日期不能大于所属里程碑及任务的计划达成日期!', 'warning')
          this.$set(this.model, 'planstartdate', null)
          return
        }
      },
      // 任务下发不走审批，修改责任人后也能重新下发（给新责任人发送消息提醒）
      distributeTask() {
        this.saveLoading = true
        this.submitLoading = true
        putAction(this.url.distributeTask, { id: this.model.id })
          .then((res) => {
            if (res.success) {
              this.$tap.message(res.message, 'success')
            } else {
              this.$tap.alert(res.message, 'warning')
            }
            this.saveLoading = false
            this.submitLoading = false
            this.$emit('refresh')
            this.visible = false
          })
          .catch((err) => {
            this.saveLoading = false
            this.submitLoading = false
          })
      },
      assignDefaultValue() {
        if (this.isAdd) {
          this.$set(this.model, 'applyorgcode', this.org.code)
          this.$set(this.model, 'applyorgname', this.org.name)
          this.$set(this.model, 'applydeptcode', this.dept.code)
          this.$set(this.model, 'applydeptname', this.dept.fullname)
          this.$set(this.model, 'applyusercode', this.user.code)
          this.$set(this.model, 'applyusername', this.user.name)
          this.$set(this.model, 'usercode', this.user.code)
          this.$set(this.model, 'username', this.user.name)
          this.$set(this.model, 'deptcode', this.dept.code)
          this.$set(this.model, 'orgcode', this.org.code)
          this.$set(this.model, 'taskschedule', '0')
          this.$set(this.model, 'taskstate', '0')
          this.$set(this.model, 'projectcode', this.projectinfo.projectcode)
          this.$set(this.model, 'projectname', this.projectinfo.projectname)
        }
      },
      // 人员选择后赋值
      addConfirm(rows, keys, values) {
        this.$set(this.model, 'responsiblecode', keys)
        this.$set(this.model, 'responsible', values)
      },
      /** 执行编辑提交 */
      doEdit() {
        this.saveLoading = true
        const param = Object.assign(this.model, { fromindex: true, singlechangeuser: this.user.code })
        putAction(this.url.edit, param)
          .then((res) => {
            if (res.success) {
              this.$tap.message(res.message, 'success')
              this.visible = false
              this.$emit('refresh')
              // 在进度页面可以修改差距与改进的信息
              if (this.fromGantt && this.$refs.feedbackRef.feedbackList.length > 0) {
                putAction(this.url.updateGap, { feedbacklist: this.$refs.feedbackRef.feedbackList }).then(res => {
                }).catch((err) => {
                  this.$tap.alert(err.message, 'warning')
                })
              }
            } else {
              this.$tap.alert(res.message, 'warning')
            }
            this.afterSubmit()
            this.saveLoading = false
          })
          .catch((err) => {
            this.saveLoading = false
          })
      },
      /** 执行编辑提交 */
      updateResponsible() {
        this.saveLoading = true
        let param = {
          id: this.model.id,
          responsiblecode: this.model.responsiblecode,
          responsible: this.model.responsible
        }
        putAction(this.url.updateResponsible, param)
          .then((res) => {
            if (res.success) {
              this.$tap.message(res.message, 'success')
              this.queryData(this.model.id)
              this.isAdd = false
            } else {
              this.$tap.alert(res.message, 'warning')
            }
            this.afterSubmit()
            this.saveLoading = false
          })
          .catch((err) => {
            this.saveLoading = false
          })
      },
      loaded() {
        // 页面加载完毕执行
        if (this.model.id && this.model.id !== 0) {
          this.$refs.feedbackRef.queryTaskFeedbackList(this.model.id)
        }
        this.externalQueryParamForStakeholder.qry_projectcode = validateNull(this.projectinfo.projectcode) ? this.projectcode : this.projectinfo.projectcode
        this.oldresponsiblecode = this.model.responsiblecode
        this.oldplanenddate = new Date(this.model.planenddate).getTime()
        // 编辑状态下才需要查询里程碑及任务,新增状态里程碑及任务的计划完成时间由reflist带出
        if (this.model.milepostcode && !this.disableEditSubmit) {
          this.queryMilepost(this.model.milepostcode)
        }
        // 判断项目是否为A级非电商其他项目
        this.checkProjectALevel()
      },
      /** 打开里程碑及任务参照 */
      openMpmProjectMilepostDialog() {
        const { projectcode } = this.model
        this.externalQueryParamForPool = {
          qry_projectcode: projectcode,
          qry_enabled: 1
          //  qry_milepoststate: 0
        }
        this.$refs.mpmProjectMilepostRef.visible = true
      },
      /** 获取里程碑及任务参照数据 */
      getMpmProjectMilepostData(selectionRow, selectKey, selectionValue) {
        this.$set(this.model, 'milepostname', selectionRow.milepostname)
        this.$set(this.model, 'milepostcode', selectionRow.operatecode)
        // 查询里程碑及任务计划达成日期
        this.milepostPlanFinishTime = selectionRow.planfinishtime
      },
      getmpmProjectStakeData(selectionRow, selectKey, selectionValue) {
        this.$set(this.model, 'responsiblecode', selectionRow.usercode)
        this.$set(this.model, 'responsible', selectionRow.username)
      },
      checkProjectALevel() {
        getAction(this.url.checkProjectALevel, { projectcode: validateNull(this.projectinfo.projectcode) ? this.model.projectcode : this.projectinfo.projectcode }).then((res) => {
          if (res.success) {
            this.projectALevelFlag = res.result
          } else {
            this.$tap.alert(res.message, 'warning')
          }
        })
      },
      // 任务保存前校验A级项目客户决策分析是否每个字段都填写了
      beforeSubmit() {
        if (this.projectALevelFlag && (validateNull(this.model.post) || validateNull(this.model.customerapproval) || validateNull(this.model.customerattach) || validateNull(this.model.needsupport) || validateNull(this.model.improveplan)) && (!validateNull(this.model.post) || !validateNull(this.model.customerapproval) || !validateNull(this.model.customerattach) || !validateNull(this.model.needsupport) || !validateNull(this.model.improveplan))) {
          this.$tap.alert('任务的客户决策分析信息须填写完整！')
          return false
        }
        return true
      },
      close() {
        this.$refs.feedbackRef.feedbackList = []
        this.$emit('refresh')
      },
      /** 格式化日期 **/
      formatDateToMicro(date) {
        return new Date(formatDate(new Date(date), 'yyyy-MM-dd')).getTime()
      }
    }
  }
</script>
